<!-- 全部订单页面1。该页面属于正常的Vue页面，正常书写代码结构，但对于订单列表这种页面来说页面性能不太好， -->
<template>
  <view v-if="shenheStatus != 1 || !shenheAliStatus" class="allorder">
    <!--  #ifdef  H5 -->
    <view v-if="isofficial() && template_id">
      <WxOpenSubscribe :template="template_id"></WxOpenSubscribe>
    </view>
    <!--  #endif  -->
    <view class="allorder-top" style="position: sticky; top: 0">
      <u-tabs
        :is-scroll="false"
        ref="uTabs"
        :list="list"
        :current="current"
        active-color="#FA230A"
        @change="tabsChange"
      ></u-tabs>
    </view>
    <scroll-view
      :scroll-y="true"
      @scrolltolower="getOrder"
      style="height: calc(100vh - 80rpx)"
    >
      <template v-if="orderList.length > 0">
        <!-- 列表渲染订单 -->
        <view v-for="(orderitem, orderindex) in orderList" :key="orderindex">
          <orderItem
            :orderitem="orderitem"
            :orderindex="orderindex"
            @toOrder="toOrder"
            @handleConfirm="handleConfirm"
            @handleCancle="handleCancle"
            @handleDelete="handleDelete"
          ></orderItem>
        </view>
      </template>
      <u-empty :text="$t('common.noDeal')" mode="list" v-else></u-empty>
      <view v-if="orderList.length > 0" style="padding-bottom: 24rpx">
        <u-loadmore
          :status="status"
          :icon-type="iconType"
          :load-text="loadText"
        />
      </view>
    </scroll-view>

    <payOrder
      ref="payOrderRef"
      :order_id="order_id"
      :order="item"
      @paySuccess="paySuccessCb"
    ></payOrder>
    <!-- <u-popup
      mode="bottom"
      v-model="show"
      border-radius="22"
      safe-area-inset-bottom
    >
      <view class="pay-top">
        <view>{{ $t("order.methods") }}</view>
        <i
          @click="show = !show"
          class="iconfont icon-close"
          style="font-size: 40rpx"
        ></i>
      </view>
      <view class="pay-way">
        <view
          v-for="(type, index) in pay_type_list"
          class="pay-way-list"
          :key="index"
          @click="payway = type.payment"
          :class="payway == type.payment ? 'select-way-list' : ''"
        >
          {{ type.name }}
        </view>
      </view>
      <view class="confrim">
        <view @click="payOrder(order_id, payway)">{{
          $t("list.confirm")
        }}</view>
      </view>
    </u-popup> -->
    <!-- 核销码展示 -->
    <u-popup
      v-model="show_qrcode"
      mode="center"
      width="80%"
      :closeable="true"
      border-radius="20"
    >
      <view
        style="
          text-align: center;
          padding: 20rpx;
          font-size: 34rpx;
          font-weight: bold;
        "
        >{{ $t("order.clerk") }}</view
      >
      <view style="display: flex; justify-content: center; padding: 30rpx">
        <image :src="qrcode_url" mode="widthFix" style="width: 500rpx"></image>
      </view>
    </u-popup>
    <u-action-sheet
      :list="cancel_list"
      :tips="{ text: $t('mdAdmin.reason') }"
      :safe-area-inset-bottom="true"
      @click="onCancel"
      v-model="is_show_calcel"
    ></u-action-sheet>
    <!-- 全局过渡组件 -->
    <transitionPage></transitionPage>
  </view>
  <Shenhe v-else-if="shenheStatus == 1"></Shenhe>
</template>

<script>
import Shenhe from "@/components/shenhe/shenhe";
import orderItem from "../components/order-list/order-item.vue";
import WxOpenSubscribe from "../components/wx-open-subscribe";
import payOrder from "../components/pay-order/pay-popup.vue";

export default {
  components: {
    orderItem,
    Shenhe,
    WxOpenSubscribe,
    payOrder
  },
  data() {
    return {
      list: [
        {
          name: this.$t("person.cashStatus1"),
          status: -1
        },
        {
          name: this.$t("person.status1"),
          status: 0
        },
        {
          name: this.$t("person.status2"),
          status: 1
        },
        {
          name: this.$t("person.status3"),
          status: 2
        },
        {
          name: this.$t("person.status4"),
          status: 3
        }
        // {
        //   name: "售后",
        //   status: 4,
        // },
      ],
      current: -1,
      orderList: [],
      page: 1,
      status: -1, // 订单状态
      pay_type_list: null, // 支付方式
      order_id: 0, // 提交支付的order_id
      show: false, // 显示支付按钮
      payway: -1, // 支付方式
      qrcode_url: "", // 核销码
      show_qrcode: false,
      is_load: true,
      template_id: [],
      routrOptions: null,
      currnetItem: null,
      is_show_calcel: false,
      cancel_id: 0,
      status: "nomore",
      iconType: "flower",
      loadText: {
        loadmore: "轻轻上拉",
        loading: "努力加载中",
        nomore: "没有更多了~"
      },

      item: null
    };
  },
  onLoad(t) {
    uni.setNavigationBarTitle({
      title: this.$t("title.order")
    });
    if (t && t.status != void 0 && t.status.length > 6) {
      t.status = parseInt(t.status.slice(7));
    }
    var status = t && t.status != void 0 ? t.status : -1;
    this.current =
      status == -1
        ? 0
        : status == 0
        ? 1
        : status == 1
        ? 2
        : status == 2
        ? 3
        : status == 3
        ? 4
        : status == 4
        ? 5
        : 0;
  },
  computed: {
    cancel_list() {
      return [
        {
          text: this.$t("mdAdmin.reason1"),
          color: "#333333",
          fontSize: 24
        },
        {
          text: this.$t("mdAdmin.reason2"),
          color: "#333333",
          fontSize: 24
        },
        {
          text: this.$t("mdAdmin.reason3"),
          color: "#333333",
          fontSize: 24
        },
        {
          text: this.$t("mdAdmin.reason4"),
          color: "#333333",
          fontSize: 24
        },
        {
          text: this.$t("mdAdmin.reason5"),
          color: "#333333",
          fontSize: 24
        }
      ];
    }
  },
  onShow() {
    try {
      const value = uni.getStorageSync("needReload");
      if (value) {
      }
      setTimeout(() => {
        uni.removeStorageSync("needReload");
      }, 0);
    } catch (e) {
      // error
    }
    // this.page = 1
    // this.orderList = []
    // this.is_load = true
  },
  watch: {
    current(val) {
      this.status = this.list[val].status;
      this.page = 1;
      this.orderList = [];
      this.is_load = true;
      this.getOrder();
    }
  },
  methods: {
    isofficial: function () {
      // #ifdef H5
      if (this.$utils.isWechat()) {
        return true;
      }
      // #endif
      return false;
    },
    onCancel(e) {
      this.$allrequest.order
        .preCancelOrder(
          {
            order_id: this.cancel_id,
            reason_id: e + 1
          },
          true
        )
        .then((res) => {
          if (res.data.resultcode == 0) {
            // #ifdef MP-ALIPAY
            if (!res.data.allow_cancel) {
              uni.showModal({
                title: "提示",
                content: "此配送单不能取消！",
                success: () => {},
                fail: () => {}
              });
              return;
            }
            // #endif

            let msg = this.$t("order.cancle");
            if (res.data.deduct_fee && res.data.deduct_fee > 0) {
              msg +=
                this.$t("mdAdmin.dedit") +
                res.data.deduct_fee +
                this.$t("mdAdmin.canWith1");
            }
            uni.showModal({
              title: this.$t("order.prompt"),
              content: msg,
              success: (ress) => {
                if (ress.confirm) {
                  this.$allrequest.order
                    .cancelOrder(
                      {
                        order_id: this.cancel_id,
                        reason_id: e + 1
                      },
                      true
                    )
                    .then((r) => {
                      if (r.data.resultcode == 0) {
                        this.orderRevoke(this.cancel_id, false);
                      } else {
                        uni.showToast({
                          title: this.$t("mdAdmin.cancleErr"),
                          duration: 2000
                        });
                      }
                    });
                }
              }
            });
          } else {
            uni.showToast({
              title: this.$t("mdAdmin.cantCancle"),
              duration: 2000
            });
          }
        });
    },
    tabsChange(index) {
      this.current = index;
    },
    getOrder() {
      if (this.is_load) {
        // #ifdef H5
        var query = {
          page: this.page,
          status: this.status,
          _from: "h5"
        };
        // #endif
        // #ifdef APP-PLUS
        var query = {
          page: this.page,
          status: this.status,
          _from: "app"
        };
        // #endif
        // #ifdef MP-WEIXIN || MP-ALIPAY || MP-TOUTIAO
        var query = {
          page: this.page,
          status: this.status,
          _from: "mini"
        };
        // #endif

        this.$allrequest.order.getList(query).then((res) => {
          if (res.code == 0) {
            if (res.data.list.length < 1) {
              this.is_load = false;
              uni.showToast({
                title: this.$t("person.end"),
                icon: "none",
                duration: 2000
              });
            } else {
              this.template_id = res.data.template_id;
              this.orderList = this.orderList.concat(res.data.list);
              this.page++;
            }
          }
        });
      } else {
      }
    },
    showPay(order_id, { item }) {
      this.$u.throttle(async () => {
        const res = await this.$allrequest.order.detail({
          longitude: "",
          latitude: "",
          order_id
        },true);
        if (!res.code) {
          let { pay_type, payOffLine } = res.data;
          if (pay_type == 11 && !payOffLine.status)
            return this.$u.toast("当前凭证正在审核，请勿重新提交");

          this.order_id = order_id;
          this.item = item;
          this.$refs.payOrderRef.setShowPopup();
        }
      }, 500);
    },
    payOrder(order_id, pay_type) {
      if (pay_type < 0) {
        uni.showToast({
          title: this.$t("order.chooseMethods"),
          icon: "none",
          duration: 2000
        });
        return false;
      }

      let params = {
        payData: {
          order_id,
          pay_type,
          order_id_list: ""
        },
        backUrl: "/order/order/order",
        pay_type_list: this.pay_type_list,
        pay_price: this.currnetItem ? this.currnetItem.pay_price : "0",
        createDate: this.currnetItem.add_time
      };
      this.$utils.toUrl(
        `/other/pay/pay?data=${JSON.stringify(params)}`,
        "redirectTo"
      );

      // this.payOrderList(
      //   {
      //     order_id: order_id,
      //     pay_type: pay_type,
      //   },
      //   (res) => {
      //     return this.$allrequest.order.payData(res);
      //   }
      // );
    },
    /**
     * 订单提交支付
     * @param {Object} data 支付内容 order_id pay_type
     * @param {Object} payData 支付接口
     */
    payOrderList(data, payData) {
      uni.showLoading({
        title: this.$t("order.pay")
      });
      // #ifdef MP-WEIXIN
      payData({
        order_id: data.order_id,
        pay_type: data.pay_type,
        _from: "mini"
      }).then((res) => {
        uni.hideLoading();
        this.paySubmit(res, data.pay_type);
      });
      // #endif

      // #ifdef APP-PLUS
      payData({
        order_id: data.order_id,
        pay_type: data.pay_type,
        _from: "app"
      }).then((res) => {
        uni.hideLoading();
        this.paySubmit(res, data.pay_type);
      });
      // #endif
    },
    paySubmit(payData, pay_type = 1) {
      if (pay_type == 3 || pay_type == 2) {
        uni.showToast({
          title: payData.msg,
          icon: "none",
          duration: 2000
        });
        if (payData.code > 0) {
          return false;
        } else {
          this.show = false;
          this.orderList = [];
          this.page = 1;
          this.getOrder();
          return true;
        }
      }
      if (!payData.data) {
        uni.showToast({
          title: payData.msg,
          icon: "none",
          duration: 2000
        });
        return false;
      } else {
        const that = this;
        uni.getProvider({
          service: "payment",
          success: function (res) {
            // 微信
            if (res.provider.indexOf("wxpay") > -1 && pay_type == 1) {
              // #ifdef MP-WEIXIN
              uni.requestPayment({
                provider: "wxpay",
                orderInfo: payData.res,
                timeStamp: payData.data.timeStamp,
                nonceStr: payData.data.nonceStr,
                package: payData.data.package,
                signType: payData.data.signType,
                paySign: payData.data.paySign,
                success: function (res) {},
                complete: function (res) {
                  if (
                    "requestPayment:fail" != res.errMsg &&
                    "requestPayment:fail cancel" != res.errMsg
                  ) {
                    uni.showToast({
                      title: this.$t("order.paySuc"),
                      icon: "none",
                      duration: 2000
                    });
                    that.show = false;
                    that.orderList = [];
                    that.page = 1;
                    that.getOrder();
                  } else {
                    uni.showToast({
                      title: this.$t("order.payFail"),
                      icon: "none",
                      duration: 2000
                    });
                  }
                }
              });
              // #endif

              // #ifdef APP-PLUS
              uni.requestPayment({
                provider: "wxpay",
                orderInfo: {
                  appid: payData.data.appid, // 微信开放平台 - 应用 - AppId，注意和微信小程序、公众号 AppId 可能不一致
                  noncestr: payData.data.noncestr, // 随机字符串
                  package: payData.data.package, // 固定值
                  partnerid: payData.data.partnerid, // 微信支付商户号
                  prepayid: payData.data.prepayid, // 统一下单订单号
                  timestamp: payData.data.timestamp, // 时间戳（单位：秒）
                  sign: payData.data.sign // 签名，这里用的 MD5 签名
                },
                success: function (res) {},
                complete: function (res) {
                  if (res.errMsg.indexOf("requestPayment:fail") == -1) {
                    uni.showToast({
                      title: this.$t("order.paySuc"),
                      icon: "none",
                      duration: 2000
                    });
                    that.show = false;
                    that.orderList = [];
                    that.page = 1;
                    that.getOrder();
                  } else {
                    uni.showToast({
                      title: this.$t("order.payFail"),
                      icon: "none",
                      duration: 2000
                    });
                  }
                }
              });
              // #endif
            }

            // 支付宝
            if (res.provider.indexOf("alipay") > -1 && pay_type == 4) {
              uni.requestPayment({
                provider: "alipay",
                orderInfo: payData.data,
                success: function (res) {},
                complete: function (res) {
                  if (res.errMsg.indexOf("requestPayment:fail") == -1) {
                    uni.showToast({
                      title: this.$t("order.paySuc"),
                      icon: "none",
                      duration: 2000
                    });
                    that.show = false;
                    that.getOrder();
                  } else {
                    uni.showToast({
                      title: this.$t("order.notPay"),
                      icon: "none",
                      duration: 2000
                    });
                  }
                }
              });
            }
          }
        });
      }
    },
    // 订单取消
    orderRevoke(order_id, show_modal) {
      var that = this;
      // #ifdef MP-WEIXIN
      uni.requestSubscribeMessage({
        tmplIds: this.template_id,
        success(res) {},
        fail(res) {},
        complete() {
          that.orderRevokeSubmit(order_id, show_modal);
        }
      });
      // #endif
      // #ifndef MP-WEIXIN
      that.orderRevokeSubmit(order_id, show_modal);
      // #endif
    },
    orderRevokeSubmit(order_id, show_modal) {
      var that = this;
      if (show_modal) {
        uni.showModal({
          title: this.$t("order.prompt"),
          content: this.$t("order.cancle"),
          success: function (res) {
            if (res.confirm) {
              that.$allrequest.order
                .revoke({
                  order_id: order_id
                })
                .then((res) => {
                  if (res.code == 0) {
                    that.page = 1;
                    that.orderList = [];
                    that.is_load = true;
                    that.getOrder();
                  } else {
                    uni.showToast({
                      title: res.msg,
                      icon: "none",
                      duration: 2000
                    });
                    return false;
                  }
                });
            } else if (res.cancel) {
            }
          }
        });
      } else {
        that.$allrequest.order
          .revoke({
            order_id: order_id
          })
          .then((res) => {
            if (res.code == 0) {
              that.page = 1;
              that.orderList = [];
              that.is_load = true;
              that.getOrder();
            } else {
              uni.showToast({
                title: res.msg,
                icon: "none",
                duration: 2000
              });
              return false;
            }
          });
      }
    },
    // 获取核销码
    getQrcode(order_no) {
      this.$allrequest.order
        .getQrcode({
          order_no: order_no
        })
        .then((res) => {
          if (res.code == 0) {
            this.qrcode_url = res.data.url;
            this.show_qrcode = true;
          } else {
            uni.showToast({
              title: res.msg,
              icon: "none",
              duration: 2000
            });
            return false;
          }
        });
    },
    // 确认收货
    confirm(order_id) {
      var that = this;
      uni.showModal({
        title: this.$t("order.prompt"),
        content: this.$t("order.goods"),
        success: function (res) {
          if (res.confirm) {
            that.$allrequest.order
              .confirm({
                order_id: order_id
              })
              .then((res) => {
                if (res.code == 0) {
                  that.page = 1;
                  that.orderList = [];
                  that.is_load = true;
                  that.getOrder();
                } else {
                  uni.showToast({
                    title: res.msg,
                    icon: "none",
                    duration: 2000
                  });
                  return false;
                }
              });
          } else if (res.cancel) {
          }
        }
      });
    },
    toComment(order_id) {
      uni.navigateTo({
        url: "/order/order-comment/order-comment?id=" + order_id
      });
    },
    toOrder(index) {
      var order = this.orderList[index];
      if (this.status == 4) {
        uni.navigateTo({
          url:
            "/order/order-refund-detail/order-refund-detail?id=" +
            order.order_refund_id
        });
      } else {
        uni.navigateTo({
          url: "/order/order-detail/order-detail?id=" + order.order_id
        });
      }
    },
    // 订单详情组件点击确认按钮
    handleConfirm(e) {
      if (e.type == this.$t("order.toPay")) {
        this.showPay(e.id, e);
        this.currnetItem = e.item || {};
      }
      if (e.type == this.$t("shop.confirm")) {
        this.confirm(e.id);
      }
      if (e.type == this.$t("order.warn")) {
      }
      if (e.type == this.$t("order.buyAgain")) {
        this.buyAgain(e.item.goods_list);
      }
    },
    // 订单详情组件点击取消按钮
    handleCancle(e) {
      if (
        e.type == this.$t("person.cancle") ||
        e.type == this.$t("order.cancleOrder")
      ) {
        if (e.is_delivery == 1 && e.is_pay == 1) {
          this.cancel_id = e.id;
          this.is_show_calcel = true;
          return;
        }
        this.orderRevoke(e.id, true);
      }
      if (e.type == this.$t("goods.evaluate")) {
        this.toComment(e.id);
      }
      if (e.type == this.$t("title.orderRefundList")) {
        uni.navigateTo({
          url: "/order/order-detail/order-detail?id=" + e.id
        });
      }
    },
    // 订单再次购买
    buyAgain(list) {
      this.$allrequest.order
        .buyAgain({ goods_list: JSON.stringify(list) }, true)
        .then((res) => {
          if (res.code == 0) {
            this.$utils.toUrl("/pages/shoppingcart/shoppingcart", "switchtab");
          }
        });
    },
    // 订单点击删除按钮
    handleDelete(e) {
      this.deleteOrder(e.id);
    },
    // 删除订单
    deleteOrder(order_id) {
      let that = this;
      uni.showModal({
        title: this.$t("order.prompt"),
        content: this.$t("mdAdmin.confirmCancle"),
        success: function (res) {
          if (res.confirm) {
            that.$allrequest.order
              .delete({
                order_id: order_id
              })
              .then((res) => {
                if (res.code == 0) {
                  that.page = 1;
                  that.orderList = [];
                  that.is_load = true;
                  that.getOrder();
                } else {
                  uni.showToast({
                    title: res.msg,
                    icon: "none",
                    duration: 2000
                  });
                  return false;
                }
              });
          } else if (res.cancel) {
          }
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.allorder {
  display: flex;
  flex-direction: column;
  // height: 100vh;
  background-color: #f2f2f2;
}

.allorder-top {
  height: 90rpx;
  background-color: #ffffff;
}

.swp {
  flex: 1;
}

.scroll-item {
  width: 100%;
  height: 100%;
}

.list-item {
  margin-top: 20rpx;
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 46rpx 35rpx 48rpx 35rpx;

  .list-item-top {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .list-item-top-left {
      display: flex;
      align-items: center;

      view {
        margin: 0rpx 10rpx;
        font-size: 30rpx;
        color: #262626;
      }

      image:first-child {
        width: 25rpx;
        height: 26rpx;
        background-color: red;
      }

      image:last-child {
        width: 12rpx;
        height: 20rpx;
        background-color: red;
      }
    }

    .list-item-top-right {
      font-size: 26rpx;
      color: #f23030;
    }
  }

  .list-item-center-one {
    margin-top: 36rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

    view:first-child {
      image {
        margin-right: 8rpx;
        width: 160rpx;
        height: 160rpx;
      }
    }

    view:last-child {
      display: flex;
      flex-direction: column;
      justify-content: flex-end;

      view:first-child {
        font-weight: bold;
        font-size: 34rpx;
        color: #262626;
      }

      view:last-child {
        margin-top: 4rpx;
        font-size: 24rpx;
        color: #8f8f8f;
      }
    }
  }

  .list-item-center-two {
    margin-top: 36rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

    view:first-child {
      display: flex;
      flex-direction: row;
      align-items: center;

      image {
        width: 160rpx;
        height: 160rpx;
      }

      view {
        flex: 1;
        margin-left: 22rpx;
        font-size: 24rpx;
        color: #262626;
        text-overflow: -o-ellipsis-lastline;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
      }
    }

    view:last-child {
      margin-left: 30rpx;
      font-size: 34rpx;
      color: #262626;
      font-weight: bold;
    }
  }

  .list-item-bottom {
    margin-top: 42rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .list-item-bottom-list {
      display: flex;
      justify-content: flex-end;

      view {
        width: 152rpx;
        height: 60rpx;
        line-height: 60rpx;
        text-align: center;
        margin-left: 22rpx;
        font-size: 26rpx;
        border-radius: 30rpx;
      }

      navigator {
        width: 152rpx;
        height: 60rpx;
        line-height: 60rpx;
        text-align: center;
        margin-left: 22rpx;
        font-size: 26rpx;
        border-radius: 30rpx;
      }

      .item-bottom-list-one {
        border: 1rpx solid #8e8e8e;
        color: #262626;
      }

      .item-bottom-list-two {
        color: #f22a10;
        border: 1rpx solid #f22a10;
      }
    }
  }
}

.list-item:last-child {
  margin-bottom: 20rpx;
}

.pay-top {
  height: 109rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0rpx 36rpx;

  view {
    font-size: 36rpx;
    font-weight: bold;
  }

  image {
    width: 40rpx;
    height: 40rpx;
  }
}

.pay-tips {
  padding: 14rpx 36rpx;
  background-color: #fbf8d9;
  font-size: 24rpx;
  color: #de6a1c;
}

.pay-way {
  padding: 24rpx 36rpx;
  display: flex;
  flex-wrap: wrap;

  .pay-way-list {
    margin-right: 24rpx;
    margin-bottom: 24rpx;
    padding: 18rpx 36rpx;
    border-radius: 30rpx;
    background-color: #f2f2f2;
    font-size: 22rpx;
    color: #bfbfbf;
  }

  .select-way-list {
    padding: 16rpx 34rpx;
    border: 1rpx solid #f2270c;
    background-color: #fcedeb;
    color: #f2270c;
  }
}

.confrim {
  margin-top: 360rpx;
  padding: 12rpx 36rpx;

  view {
    width: 100%;
    height: 76rpx;
    line-height: 76rpx;
    text-align: center;
    font-size: 30rpx;
    color: #ffffff;
    background: linear-gradient(90deg, #f3150c, #f14b0c);
    border-radius: 38rpx;
  }
}

::v-deep {
  .list-item {
    border-radius: 0;
  }
}
</style>
